// Copyright 2007 Google Inc. All Rights Reserved.

package com.google.jessewilson.codesearch.ide;

import com.google.inject.Inject;
import com.google.jessewilson.codesearch.api.DefaultQueryResponse;
import com.google.jessewilson.codesearch.api.Query;
import com.google.jessewilson.codesearch.api.QueryResponse;
import com.google.jessewilson.codesearch.api.QueryRunner;
import com.google.jessewilson.codesearch.api.ResultsDisplayer;
import com.google.jessewilson.codesearch.api.spi.SearchProviderBackend;

/**
 * @author jessewilson
 */
public class DefaultQueryRunner implements QueryRunner {

  private final QueryHistory queryHistory;
  private final ResultsDisplayer resultsDisplayer;
  private final DefaultQueryResponse.Factory defaultQueryResponseFactory;

  @Inject
  public DefaultQueryRunner(
      QueryHistory queryHistory,
      ResultsDisplayer resultsDisplayer,
      DefaultQueryResponse.Factory defaultQueryResponseFactory) {
    this.queryHistory = queryHistory;
    this.resultsDisplayer = resultsDisplayer;
    this.defaultQueryResponseFactory = defaultQueryResponseFactory;
  }

  public void query(Query query, SearchProviderBackend searchProviderBackend) {
    // remember this event in history
    queryHistory.postQuery(query);

    // create a new results with the old lines and the new term
    QueryResponse queryResponse = defaultQueryResponseFactory.create(
        query, searchProviderBackend);

    // display the query
    resultsDisplayer.displayResults(queryResponse);
    queryResponse.getResultsPopulator().fetchMoreResults();
  }
}
